package com.longfor.dragonshard.service.impl;

import com.longfor.daenerys.config.LFProperties;
import com.longfor.dragonshard.common.enums.BizEnum;
import com.longfor.dragonshard.dto.account.LoginDTO;
import com.longfor.dragonshard.entity.DemoAccount;
import com.longfor.dragonshard.mapper.DemoAccountMapper;
import com.longfor.dragonshard.service.IDemoAccountService;
import com.longfor.dragonshard.service.ILoginService;
import com.longfor.dragonshard.service.IValidateService;
import com.longfor.dragonshard.service.base.AbstractBaseService;
import com.longfor.drogon.common.LFConstants;
import com.longfor.drogon.common.exception.LFBizException;
import com.longfor.drogon.common.util.LFDefaultKeyGenerator;
import com.longfor.drogon.common.util.LFJwt;
import com.longfor.drogon.common.util.LFUtils;
import org.apache.commons.codec.DecoderException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.util.Optional;

/**
 * Login Service类
 *
 * @author chi.zhang
 * @version v1.0
 * @create 2017-10-05 下午2:28
 **/
@Service
public class LoginServiceImpl implements ILoginService {
    private Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);

    @Autowired
    private LFProperties lfProperties;
    @Autowired
    private IValidateService validateService;
    @Autowired
    private DemoAccountMapper demoAccountMapper;

    @Override
    public String doLogin(LoginDTO loginDTO) {
        //校验验证码
        if (lfProperties.getValidateCode().getEnabled()) {
            validateService.checkValidate(loginDTO.getValidateKey(), loginDTO.getValidateCode());
        }

        //判断用户是否存在及状态是否可用
        DemoAccount demoAccount = new DemoAccount();
        demoAccount.setUsername(loginDTO.getUserName());
        demoAccount = demoAccountMapper.selectOne(demoAccount);
        if (demoAccount == null) {
            //用户名或密码错误
            throw new LFBizException(BizEnum.E9902.getText());
        }
        if (demoAccount.getStatus() == 0) {
            //用户状态不可用
            throw new LFBizException(BizEnum.E9906.getText());
        }

        String rawPassword = loginDTO.getPassword();
        //如果开启了RSA加密，则解密登录密码
        if (lfProperties.getAdmin().getLogin().getRsaEncrypt()) {
            rawPassword = LFUtils.decryptRSAPassword(
                    lfProperties.getAdmin().getLogin().getPrivateExponent(),
                    lfProperties.getAdmin().getLogin().getModulus(),
                    loginDTO.getPassword()
            );
        }

        //校验登录密码
        boolean isSuccess = false;
        try {
            isSuccess = LFUtils.checkDefaultLoginPassword(rawPassword, demoAccount.getPassword());
            if(!isSuccess){
                throw new LFBizException(BizEnum.E9902.getText());
            }
        } catch (DecoderException e) {
            e.printStackTrace();
            logger.debug("==LF==登录密码SHA校验失败");
            throw new LFBizException();
        }

        //生成Token
        String token = null;
        try {
            token = LFJwt.createJWT(
                    demoAccount.getUsername(),
                    "",
                    "",
                    LFConstants.SECURITY.EAP_DEFAULT_TOKEN_VALIDITY_TIME,
                    lfProperties.getAdmin().getEncrypt().getAesKey()
            );
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            logger.debug("==LF==生成JWT-TOKEN失败");
            throw new LFBizException();
        }

        return token;
    }
}
